package com.yang.handler.security;

import com.alibaba.fastjson.JSON;
import com.yang.domain.Result;
import com.yang.enums.AppHttpCodeEnum;
import com.yang.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 * @author yang
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint{

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        authException.printStackTrace();

        Result result;
        //1.判断异常类型
        if (authException instanceof BadCredentialsException){
            //说明认证出现了异常，可能是用户名或密码错误
            result = Result.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),authException.getMessage());

        }else if (authException instanceof InsufficientAuthenticationException){
            //说明授权出现了异常，可能是没有登录
            result =Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else {
            result = Result.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"出现了未知的异常，请联系管理员");
        }

        //2.响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
